//引入express模块
var express = require('express');
//创建APP
var app = express();
//创建Server
var server = require('http').createServer(app);
//引入body-parser用来接收post请求的数据
var bodyParser = require('body-parser');
//引入MD5加密模块
var md5 = require('./md5');
//引入用户数据源
var users = require('./datasource/user');
// 引入multer模块（文件上传）
var multer = require('multer');
// 引入文件模块('fs')
var fs = require('fs')
// photo：就是页面是你传过来的的name,1代表最多能传一个
app.use(multer({
  dest: 'tmp'
}).array('photo', 1));
//引入PATH
var path = require('path');
//解析POST数据
app.use(bodyParser.urlencoded({
  extended: true
}))
// 引入rimraf模块
const rimraf = require('rimraf')

//托管静态文件
app.use(express.static(__dirname + '/src'));

//网站的入口
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/src/pages/index.html');
})

//登录
app.post('/login.do', (req, res) => {
  let username = req.body.username;
  let password = md5(req.body.password);

  if (!username || !password) {
    res.send('fail');
    return;
  }

  for (u of users) {
    if (u.username === username && u.password === password && u.state == 1) {
      res.send('success');
      return;
    }
  }
  res.send('fail');
})
// ==========================================================================================
//查询用户列表
app.get('/users.do', (req, res) => {
  res.send(users);
})


//重置用户密码
app.post('/resetPass.do', (req, res) => {
  let id = req.body.id;
  let new_pass = req.body.password;
  for (u of users) {
    if (u.id == id) {
      u.password = md5(new_pass);
      res.send('success');
      return;
    }
  }
  res.send('fail');
})

//修改用户状态(1:正常；0:冻结)
app.post('/change_state.do', (req, res) => {
  let id = req.body.id;
  let state = req.body.state;
  for (u of users) {
    if (u.id == id) {
      u.state = state;
      res.send('success');
      return;
    }
  }
  res.send('fail');
})


//添加新用户
app.post('/addUser.do', (req, res) => {
  let username = req.body.username;
  let password = md5(req.body.password);
  let phone = req.body.phone;
  let id = users[users.length - 1].id + 1;
  let state = 1;
  if (username && password && phone) {
    users.push({
      username,
      password,
      phone,
      id,
      state
    });
    res.send('success');
  } else {
    res.send('sail');
  }
});

// =========================================================================================

// 引入角色数据
var roles = require('./datasource/role')
//查询角色列表
app.get('/role.do', function (req, res) {
  res.send(roles);
})

// 添加新角色

app.post('/roles.do', (req, res) => {
  let role = req.body.username;
  //判断用户是否已添加
  for (rol of role) {
    if (rol == role) {
      res.send('no');
      return;
    }
  }
  if (role) {
    roles.push(role);
    res.send('success');
  } else {
    res.send('fail');
  }
});
// =========================================================================================
// 引入员工数据源
var empl = require('./datasource/employee')
// 查询员工列表
app.get('/employee.do', function (req, res) {
  for (var i = 0; i < empl.length; i++) {
    if (empl[i].state != 1) {
      empl.splice(i, 1);
    }
  }
  res.send(empl);
})

// 删除员工
app.post('/empls.do', (req, res) => {
  let id = req.body.id;
  for (let index = 0; index < empl.length; index++){
    let value = empl[index];
    if(value.id == id){
      let url = __dirname+'/src/assets/img'+value.photo;
      try{
        fs.unlinkSync(url);
      }catch(error){
        fs.appendFile(__dirname+'/log/error.txt',error.message,(err)=>{
          if(err) throw err;
        });
        res.send('fail');
        return;
      }
      empl.splice(index,1);
      res.send('success');
      return;
    }
  }
res.send('fail')
})

app.get('/query.do',(req,res)=>{
let id = req.query.id;
let newArr = empl.filter(value=>{
  return value.id == id;
})
console.log(newArr);
res.send(newArr[0]);
})

/******************************************************************************************* */
//添加
app.post('/employee_2.do', (req, res) => {
  var file = req.files[0];
  //获取原始文件的名字
  var url = __dirname + '/src/assets/img/' + file.originalname;
  // 读取数据
  var data = fs.readFileSync(file.path);

  fs.writeFile(url, data, function (err) {
    if (err) {
      console.error(err);
    }
    rimraf(__dirname + '/tmp/*', function (err) {
      // console.log(err);
    })
  })
  let id = empl[empl.length - 1].id + 1;
  let em = {
    id,
    name: req.body.name,
    age: req.body.age,
    sex: req.body.sex,
    phone: req.body.phone,
    idCard: req.body.idCard,
    role: req.body.role,
    photo: file.originalname,
    state: req.body.state
  }
  console.log(em);
  empl.push(em);
  res.send('success');
})


server.listen(8888);
console.log('=====Hotel Manage Startup Success in 8888=====');